﻿using Furion.DatabaseAccessor;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using JoyAdmin.Core;
using JoyAdmin.Core.Entities.System; 
using Microsoft.AspNetCore.Authorization;
using System;
using System.Collections.Generic;
using System.Linq;  
using Furion.Utilities;
using Serilog;
using Mapster;

namespace JoyAdmin.Application.System
{


    public class SystemService : IDynamicApiController
    {
        private readonly ILogger _logger;
        private readonly IRepository<SysArea, MultiTenantDbContextLocator> _areaRepository;
        private readonly IRepository<SysTenant, MultiTenantDbContextLocator> _tenantRepository;
        public SystemService( 
            ILogger logger
            ,IRepository<SysArea, MultiTenantDbContextLocator> areaRepository
            , IRepository<SysTenant, MultiTenantDbContextLocator>  tenantRepository)
        {
            _logger = logger;
            _areaRepository = areaRepository;
            _tenantRepository = tenantRepository;
        }
        /// <summary>
        /// 查看地区
        /// </summary>

        [AllowAnonymous]
        public List<AreaDto> GetArea()
        {
           var areas= _areaRepository.Where(m=>m.IsDeleted==false).ToList(); 
            return areas.Adapt<List<AreaDto>>();
        }
         
        /// <summary>
        /// 保存地区
        /// </summary>
        [SecurityDefine(SecurityConst.S_System)]
        public bool SaveArea(AreaDto input)
        {
            _areaRepository.InsertOrUpdate(input.Adapt<SysArea>());
             return true; 
        }
        /// <summary>
        /// 删除地区
        /// </summary>
        [SecurityDefine(SecurityConst.S_System)]
        public bool DeleteArea(long id)
        {
            _areaRepository.FakeDelete(id);
            return true;
        }

        /// <summary>
        /// 查看租户信息
        /// </summary>
         
        [SecurityDefine(SecurityConst.S_System)]
        public PagedList<SysTenant> SearchTenant(TenantInput input)
        {
            var search = _tenantRepository.Where(m => m.IsDeleted == false);
            if (input.areaid>0)
            {
                search= search.Where(m => m.AreaId == input.areaid);
            }
            if (!string.IsNullOrEmpty(input.name))
            {
                search = search.Where(m => m.Name.Contains(input.name));
            }
            var areas = search.ToPagedList(input.page, input.size);
            return areas;
        }
        /// <summary>
        /// 删除租户信息
        /// </summary>
        [SecurityDefine(SecurityConst.S_System)]
        public bool DeleteTenant(long id)
        {
            _tenantRepository.FakeDelete(id);
            return true;
        }
        /// <summary>
        /// 保存租户信息
        /// </summary>
        [SecurityDefine(SecurityConst.S_System)]
        public bool SaveTenant(SysTenant info)
        {
            
            if (info.Id <= 0)
            {
                var tenant = _tenantRepository.Where(m => m.IsDeleted == false && m.Host == info.Host).FirstOrDefault();
                if (tenant!=null)
                {
                    throw Oops.Oh(ErrorCode.WrongValidation,"该主机地址已存在").StatusCode(ErrorStatus.ValidationFaild);
                }
                info.TenantId = Guid.NewGuid();
                _tenantRepository.Insert(info);
            }
            else {
                var tenant = _tenantRepository.Where(m => m.IsDeleted == false && m.Host == info.Host&&m.Id!=info.Id).FirstOrDefault();
                if (tenant != null)
                {
                    throw Oops.Oh(ErrorCode.WrongValidation, "该主机地址已存在").StatusCode(ErrorStatus.ValidationFaild);
                }
                _tenantRepository.UpdateExclude(info, new[] { nameof(info.Host) });
            }
          
            return true;
        } 
       
        /// <summary>
        /// 测试错误
        /// </summary>
        [AllowAnonymous]
        public dynamic GetTestError()
        {
            throw Oops.Oh("出错了，OOPS");
        }
        /// <summary>
        /// 保存前端错误
        /// </summary>
        [AllowAnonymous]
        public bool SaveErrorLogger(dynamic info)
        { 
            _logger.Error(JsonSerializerUtility.Serialize(info));
            return true;
        }
        /// <summary>
        /// 测试void
        /// </summary>
        [AllowAnonymous]
        public void testvoid()
        {
           
        }
    }
}
